package com.rightsidetech.commom.utils;

import lombok.extern.slf4j.Slf4j;
import org.wltea.expression.ExpressionEvaluator;
import org.wltea.expression.PreparedExpression;
import org.wltea.expression.datameta.Variable;

import java.util.*;

@Slf4j
public class IKExpressionUtil {

    private IKExpressionUtil(){}

    public static boolean executeIs(String expression, Map<String,Object> map){
        List<Variable> variables = new ArrayList<>();
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            variables.add(Variable.createVariable(s,map.get(s)));
        }
        try {
            PreparedExpression pe = ExpressionEvaluator.preparedCompile(expression, variables);
            Object result = pe.execute();
            if(result instanceof Boolean){
                return (Boolean) result;
            }
        }catch (Exception e){
            log.error("规则执行出现异常 {}",e);
            e.printStackTrace();
        }
        return false;
    }

    public static Integer executeInt(String expression, Map<String,Object> map){
        List<Variable> variables = new ArrayList<>();
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            variables.add(Variable.createVariable(s,map.get(s)));
        }
        try {
            PreparedExpression pe = ExpressionEvaluator.preparedCompile(expression, variables);
            Object result = pe.execute();
            if(result instanceof Integer){
                return (Integer) result;
            }
        }catch (Exception e){
            log.error("规则执行出现异常 {}",e);
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("date",new Date());
//        boolean execute = executeIs("a == b && a <= c", map);
        System.out.println(executeIs("date<=[2022-03-27]",map));
    }
}
